<template>
  <el-dialog
    v-model="visible"
    title="⚡ 一键智能创建访客单"
    width="800px"
    @close="handleClose"
  >
    <el-alert
      type="info"
      :closable="false"
      style="margin-bottom: 20px"
    >
      <template #title>
        <span style="font-size: 14px">💡 快捷模式：输入带看情况，AI自动提取满意度、意向度、优缺点等信息</span>
      </template>
    </el-alert>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <!-- 核心必填字段 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item
            label="客户"
            prop="lead_id"
          >
            <el-select
              v-model="formData.lead_id"
              filterable
              placeholder="输入客户姓名或手机号"
              style="width: 100%"
              :loading="loadingLeads"
              @focus="loadLeads"
            >
              <el-option
                v-for="lead in leads"
                :key="lead.id"
                :label="`${lead.name} - ${lead.phone}`"
                :value="lead.id"
              >
                <span>{{ lead.name }}</span>
                <span style="color: #8492a6; font-size: 12px; margin-left: 8px">
                  {{ lead.phone }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="房源"
            prop="property_id"
          >
            <el-select
              v-model="formData.property_id"
              filterable
              placeholder="输入小区名或房号"
              style="width: 100%"
              :loading="loadingProperties"
              @focus="loadProperties"
              @change="handlePropertyChange"
            >
              <el-option
                v-for="property in properties"
                :key="property.id"
                :label="`${property.community_name} ${property.room_number}`"
                :value="property.id"
              >
                <span>{{ property.community_name }}</span>
                <span style="color: #8492a6; font-size: 12px; margin-left: 8px">
                  {{ property.room_number }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item
            label="经纪人"
            prop="agent_id"
          >
            <el-select
              v-model="formData.agent_id"
              filterable
              placeholder="选择经纪人"
              style="width: 100%"
              :loading="loadingAgents"
              @focus="loadAgents"
            >
              <el-option
                v-for="agent in agents"
                :key="agent.id"
                :label="agent.full_name || agent.email"
                :value="agent.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="带看日期"
            prop="visit_date"
          >
            <el-date-picker
              v-model="formData.visit_date"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 带看情况输入框（核心） -->
      <el-form-item
        label="带看情况"
        prop="quick_notes"
      >
        <el-input
          v-model="formData.quick_notes"
          type="textarea"
          :rows="4"
          placeholder="请描述带看情况，例如：今天下午2点带看了望京SOHO，客户非常满意，特别喜欢采光和户型。但是觉得租金有点贵。大概看了45分钟。客户表示想尽快租下来。"
          maxlength="2000"
          show-word-limit
          @input="handleNotesInput"
        />
        <div
          v-if="extracting"
          style="margin-top: 8px; color: #409eff; font-size: 12px"
        >
          <el-icon class="is-loading">
            <Loading />
          </el-icon>
          AI正在分析带看情况...
        </div>
        <div
          v-if="extractionInfo"
          style="margin-top: 8px; color: #67c23a; font-size: 12px"
        >
          ✓ AI分析完成 | 置信度: {{ (extractionInfo.confidence * 100).toFixed(0) }}% | 方法: {{ extractionMethodText }}
        </div>
      </el-form-item>

      <!-- AI提取结果预览区（可编辑） -->
      <el-divider content-position="left">
        <el-text
          type="primary"
          size="small"
        >
          AI提取结果（可编辑）
        </el-text>
      </el-divider>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item
            label="满意度"
            prop="satisfaction"
          >
            <el-rate
              v-model="formData.satisfaction"
              show-score
              text-color="#ff9900"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="意向度"
            prop="intention"
          >
            <el-select
              v-model="formData.intention"
              placeholder="请选择意向度"
              style="width: 100%"
            >
              <el-option
                label="高"
                value="high"
              />
              <el-option
                label="中"
                value="medium"
              />
              <el-option
                label="低"
                value="low"
              />
              <el-option
                label="无"
                value="none"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item
            label="带看时间"
            prop="visit_time"
          >
            <el-time-picker
              v-model="formData.visit_time"
              placeholder="AI提取或手动选择"
              value-format="HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="停留时长"
            prop="duration_minutes"
          >
            <el-input-number
              v-model="formData.duration_minutes"
              :min="0"
              :max="1440"
              placeholder="分钟"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item
        label="优点标签"
        prop="pros_tags"
      >
        <el-input
          v-model="formData.pros_tags"
          placeholder="AI自动提取或手动输入（逗号分隔）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        label="缺点标签"
        prop="cons_tags"
      >
        <el-input
          v-model="formData.cons_tags"
          placeholder="AI自动提取或手动输入（逗号分隔）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit"
      >
        ⚡ 智能创建
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({ name: 'VisitorSheetQuickDialog' })
/**
 * 访客单快捷创建对话框 (Phase 2)
 * 一键智能创建：AI自动提取满意度、意向度、优缺点等信息
 */
import { ref, reactive, computed, watch } from 'vue'
import { Loading } from '@element-plus/icons-vue'
import { useVisitorSheetStore } from '@/stores/visitor-sheet'
import { useUserStore } from '@/stores/user'
import type { FormInstance, FormRules } from 'element-plus'
import type { Lead, Property, User } from '@/api/types'
import { leadApi, propertyApi, visitorSheetApi } from '@/api'
import notify from '@/utils/notify'
import { debounce } from 'lodash-es'

// ========== Props & Emits ==========
interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// ========== Store ==========
const visitorSheetStore = useVisitorSheetStore()
const userStore = useUserStore()

// ========== 响应式数据 ==========
const visible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const extracting = ref(false)

// 下拉列表数据
const leads = ref<Lead[]>([])
const properties = ref<Property[]>([])
const agents = ref<User[]>([])

// 加载状态
const loadingLeads = ref(false)
const loadingProperties = ref(false)
const loadingAgents = ref(false)

// AI提取信息
interface ExtractionInfo {
  confidence: number
  extraction_method: string
  satisfaction?: number
  intention?: string
  pros_tags?: string
  cons_tags?: string
  visit_time?: string
  duration_minutes?: number
}
const extractionInfo = ref<ExtractionInfo | null>(null)
const selectedCommunityName = ref<string>('')

const formData = reactive({
  lead_id: 0,
  property_id: 0,
  agent_id: 0,
  visit_date: '',
  quick_notes: '',
  // AI提取字段
  satisfaction: undefined as number | undefined,
  intention: 'medium' as string,
  pros_tags: '',
  cons_tags: '',
  visit_time: undefined as string | undefined,
  duration_minutes: undefined as number | undefined,
})

// 表单验证规则
const rules: FormRules = {
  lead_id: [
    { required: true, message: '请选择客户', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择客户', trigger: 'change' },
  ],
  property_id: [
    { required: true, message: '请选择房源', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择房源', trigger: 'change' },
  ],
  agent_id: [
    { required: true, message: '请选择经纪人', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择经纪人', trigger: 'change' },
  ],
  visit_date: [{ required: true, message: '请选择带看日期', trigger: 'change' }],
  quick_notes: [
    { required: true, message: '请输入带看情况', trigger: 'blur' },
    { min: 10, message: '至少输入10个字符以便AI分析', trigger: 'blur' },
  ],
}

// 提取方法文本映射
const extractionMethodText = computed(() => {
  if (!extractionInfo.value) return ''
  const method = extractionInfo.value.extraction_method
  const map: Record<string, string> = {
    rules: '规则引擎',
    hybrid: '混合模式',
    ai: 'AI语义分析',
  }
  return map[method] || method
})

// ========== 方法 ==========

/**
 * 加载客户列表
 */
const loadLeads = async () => {
  if (leads.value.length > 0) return
  loadingLeads.value = true
  try {
    const res = await leadApi.getList({ page: 1, page_size: 200 })
    leads.value = res.items
  } catch (error) {
    console.error('加载客户列表失败', error)
    notify.error('加载客户列表失败')
  } finally {
    loadingLeads.value = false
  }
}

/**
 * 加载房源列表
 */
const loadProperties = async () => {
  if (properties.value.length > 0) return
  loadingProperties.value = true
  try {
    const res = await propertyApi.getList({ page: 1, page_size: 100 })
    properties.value = res.items
  } catch (error) {
    console.error('加载房源列表失败', error)
    notify.error('加载房源列表失败')
  } finally {
    loadingProperties.value = false
  }
}

/**
 * 加载经纪人列表
 */
const loadAgents = async () => {
  if (agents.value.length > 0) return
  loadingAgents.value = true
  try {
    if (userStore.userInfo) {
      agents.value = [userStore.userInfo]
      if (!formData.agent_id) {
        formData.agent_id = userStore.userInfo.id
      }
    }
  } catch (error) {
    console.error('加载经纪人列表失败', error)
    notify.error('加载经纪人列表失败')
  } finally {
    loadingAgents.value = false
  }
}

/**
 * 处理房源选择变化
 */
const handlePropertyChange = (propertyId: number) => {
  const property = properties.value.find(p => p.id === propertyId)
  if (property) {
    selectedCommunityName.value = property.community_name
    // 如果已有备注，重新提取
    if (formData.quick_notes.length >= 10) {
      extractInfoFromNotes(formData.quick_notes)
    }
  }
}

/**
 * AI提取访客单信息（防抖处理）
 */
const extractInfoFromNotes = debounce(async (notes: string) => {
  if (notes.length < 10) return

  extracting.value = true
  try {
    const params: { notes: string; community_name?: string } = { notes }
    if (selectedCommunityName.value) {
      params.community_name = selectedCommunityName.value
    }

    const result = await visitorSheetApi.extractInfo(params)
    extractionInfo.value = result

    // 自动填充提取结果（用户可编辑）
    if (result.satisfaction) {
      formData.satisfaction = result.satisfaction
    }
    if (result.intention) {
      formData.intention = result.intention
    }
    if (result.pros_tags) {
      formData.pros_tags = result.pros_tags
    }
    if (result.cons_tags) {
      formData.cons_tags = result.cons_tags
    }
    if (result.visit_time) {
      formData.visit_time = result.visit_time
    }
    if (result.duration_minutes) {
      formData.duration_minutes = result.duration_minutes
    }
  } catch (error) {
    console.error('AI提取失败', error)
    notify.warning('AI提取失败，请手动填写')
  } finally {
    extracting.value = false
  }
}, 1000)

/**
 * 处理带看情况输入
 */
const handleNotesInput = (value: string) => {
  extractInfoFromNotes(value)
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    loading.value = true
    try {
      // 调用快捷创建API
      const quickCreateData = {
        lead_id: formData.lead_id,
        property_id: formData.property_id,
        agent_id: formData.agent_id,
        visit_date: formData.visit_date,
        quick_notes: formData.quick_notes,
        // 用户编辑后的字段
        satisfaction: formData.satisfaction,
        intention: formData.intention,
        pros_tags: formData.pros_tags,
        cons_tags: formData.cons_tags,
        visit_time: formData.visit_time,
        duration_minutes: formData.duration_minutes,
      }

      const result = await visitorSheetApi.quickCreate(quickCreateData)

      if (result) {
        notify.success('访客单创建成功')
        // 刷新列表
        await visitorSheetStore.fetchVisitorSheets()
        emit('success')
        handleClose()
      }
    } catch (error: unknown) {
      console.error('创建失败', error)
      const axiosError = error as { response?: { data?: { detail?: string } } }
      notify.error(axiosError.response?.data?.detail || '创建失败')
    } finally {
      loading.value = false
    }
  })
}

/**
 * 关闭对话框
 */
const handleClose = () => {
  formRef.value?.resetFields()
  extractionInfo.value = null
  selectedCommunityName.value = ''
  visible.value = false
}

/**
 * 初始化表单数据
 */
const initFormData = () => {
  Object.assign(formData, {
    lead_id: 0,
    property_id: 0,
    agent_id: userStore.userInfo?.id || 0,
    visit_date: '',
    quick_notes: '',
    satisfaction: undefined,
    intention: 'medium',
    pros_tags: '',
    cons_tags: '',
    visit_time: undefined,
    duration_minutes: undefined,
  })
}

// ========== 监听 ==========
watch(visible, (newVal) => {
  if (newVal) {
    initFormData()
    loadLeads()
    loadProperties()
    loadAgents()
  }
})
</script>

<style scoped>
.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
